﻿using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using VisionDesigner;
using VM.Common.Enums;
using VM.Common.EventMgrLib;
using VM.Common.Helper;
using VM.Dialogs.Views;
using VM.Start.Attributes;
using VM.Start.Common;
using VM.Start.Controls;
using VM.Start.Core;
using VM.Start.Events;
using VM.Start.ViewModels;

namespace Plugin.BeadGuide
{
    #region enum
    [Serializable]
    public enum eLinkCommand
    {
        InputImageLink,
        PositionFix
    }

    [Serializable]
    public enum eOperateCommand
    {
        创建,
        编辑,
    }

    #endregion

    [Serializable]
    public class TemplateModel : NotifyPropertyBase
    {
        // 模板的序号
        private int _index;
        public int Index
        {
            get => _index;
            set => Set(ref _index, value);
        }

        // 模板的名称
        private string _name;
        public string Name
        {
            get => _name;
            set => Set(ref _name, value);
        }

        public BeadGuideEditViewModel Data { get; set; } // 模板数据
    }


    [Category("检测识别")]
    [DisplayName("路径提取")]
    [ModuleImageName("BeadGuide")]
    [JsonObject(MemberSerialization.OptOut)]
    public class BeadGuideViewModel : ModuleBase
    {
        #region 属性

        // 绘制轮廓
        private List<CMvdPointSetF> _DrawOutlineList = new List<CMvdPointSetF>();

        #endregion
        #region 数据接口

        private int _selectedTabIndex;
        public int SelectedTabIndex
        {
            get => _selectedTabIndex;
            set
            {
                _selectedTabIndex = value;
                RaisePropertyChanged(); // 通知属性更新
            }
        }


        [Newtonsoft.Json.JsonIgnore]
        public VMDisplayControl _MatchWindow;
        [Newtonsoft.Json.JsonIgnore]
        public VMDisplayControl MatchWindow
        {
            get
            {
                if (_MatchWindow == null)
                {
                    _MatchWindow = new VMDisplayControl();
                }
                return _MatchWindow;
            }
        }

        public TemplateModel _selectedTemplate;
        public TemplateModel SelectedTemplate
        {
            get
            {
                return _selectedTemplate;
            }
            set
            {
                Set(ref _selectedTemplate, value);
                if (_selectedTemplate != null)
                {
                    MatchWindow.Copy(_selectedTemplate.Data.TemplateWindow);
                }
                else
                {
                    MatchWindow.Clear();
                    MatchWindow.Image = null;
                }
            }
        }

        private ObservableCollection<TemplateModel> _templateList = new ObservableCollection<TemplateModel>();
        public ObservableCollection<TemplateModel> TemplateList
        {
            get { return _templateList; }
            set { Set(ref _templateList, value); }
        }

        #endregion
        #region 指令

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _LinkCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase LinkCommand
        {
            get
            {
                if (_LinkCommand == null)
                {
                    //以GUID+类名作为筛选器
                    EventMgr.Ins
                        .GetEvent<VarChangedEvent>()
                        .Subscribe(OnVarChanged, o => o.SendName.StartsWith($"{ModuleGuid}"));
                    _LinkCommand = new CommandBase(
                        (obj) =>
                        {
                            eLinkCommand linkCommand = (eLinkCommand)obj;
                            switch (linkCommand)
                            {
                                case eLinkCommand.InputImageLink:
                                    CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "Image");
                                    EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},InputImageLink");
                                    break;
                                case eLinkCommand.PositionFix:
                                    CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "CPositionFixTool");
                                    EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},PositionFix");
                                    break;
                                default:
                                    break;
                            }

                        }
                    );
                }
                return _LinkCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _OperateCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase OperateCommand
        {
            get
            {
                if (_OperateCommand == null)
                {
                    _OperateCommand = new CommandBase(
                        (obj) =>
                        {
                            try
                            {
                                eOperateCommand par = (eOperateCommand)obj;
                                switch (par)
                                {
                                    case eOperateCommand.创建:
                                        try
                                        {
                                            BeadGuideEditViewModel editViewModel = new BeadGuideEditViewModel();
                                            BeadGuideEditView editView = new BeadGuideEditView
                                            {
                                                DataContext = editViewModel
                                            };
                                            editViewModel.view = editView;
                                            editViewModel.LocalImage = DispImage;
                                            editViewModel.beadGuideViewModel = this;
                                            var view = this.ModuleView as BeadGuideView;
                                            editView.Owner = view;
                                            editView.ShowDialog();
                                        }
                                        catch (MvdException ex)
                                        {
                                            if (ex.ErrorCode == MVD_ERROR_CODE.MVD_E_RUNTIME)
                                            {
                                                MessageView.Ins.MessageBoxShow("运行环境异常，请停止项目并检查加密狗！", eMsgType.Error);
                                            }
                                            else
                                            {
                                                MessageView.Ins.MessageBoxShow("创建实例失败！", eMsgType.Error);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            // 记录日志或显示错误消息
                                            MessageView.Ins.MessageBoxShow($"创建操作失败: {ex.Message}", eMsgType.Error);
                                        }
                                        break;
                                    case eOperateCommand.编辑:
                                        try
                                        {
                                            if (SelectedTemplate != null && SelectedTemplate.Data != null)
                                            {
                                                BeadGuideEditView editView = new BeadGuideEditView
                                                {
                                                    DataContext = SelectedTemplate.Data
                                                };
                                                SelectedTemplate.Data.LocalImage = DispImage;
                                                SelectedTemplate.Data.view = editView;
                                                SelectedTemplate.Data.beadGuideViewModel = this;
                                                SelectedTemplate.Data.m_TemplateModel = SelectedTemplate;
                                                var view = this.ModuleView as BeadGuideView;
                                                editView.Owner = view;
                                                SelectedTemplate.Data.Loaded();
                                                editView.ShowDialog();
                                            }
                                        }
                                        catch
                                        {

                                        }
                                        break;
                                    default:
                                        throw new ArgumentOutOfRangeException();
                                }
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    );
                }
                return _OperateCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ExecuteCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ExecuteCommand
        {
            get
            {
                if (_ExecuteCommand == null)
                {
                    _ExecuteCommand = new CommandBase(
                        (obj) =>
                        {
                            ExeModule();
                        }
                    );
                }
                return _ExecuteCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ConfirmCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ConfirmCommand
        {
            get
            {
                if (_ConfirmCommand == null)
                {
                    _ConfirmCommand = new CommandBase(
                        (obj) =>
                        {
                            var view = this.ModuleView as BeadGuideView;
                            if (view != null)
                            {
                                view.Close();
                            }
                        }
                    );
                }
                return _ConfirmCommand;
            }
        }

        #endregion
        #region  方法

        public override void Loaded()
        {
            base.Loaded();
            ClosedView = true;
            foreach (var item in TemplateList)
            {
                item.Data.Loaded();
            }
            var matchingItem = TemplateList.FirstOrDefault(item => item.Name == SelectedTemplate.Name && item.Index == SelectedTemplate.Index);
            SelectedTemplate = matchingItem;

        }

        public override void SetDefaultLink()
        {
            if (InputImageLinkText == null)
            {
                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "Image");
                var moduls = VarLinkViewModel.Ins.Modules.LastOrDefault();
                if (moduls?.VarModels.Count > 0)
                {
                    InputImageLinkText = $"&{moduls.DisplayName}.{moduls.VarModels[0].Name}";
                }
            }

            if (PositionFixText == null)
            {
                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "CPositionFixTool");
                var moduls = VarLinkViewModel.Ins.Modules.LastOrDefault();
                if (moduls?.VarModels.Count > 0)
                {
                    PositionFixText = $"&{moduls.DisplayName}.{moduls.VarModels[0].Name}";
                }
            }
        }

        private void OnVarChanged(VarChangedEventParamModel obj)
        {
            switch (obj.SendName.Split(',')[1])
            {
                case "InputImageLink":
                    InputImageLinkText = obj.LinkName;
                    if (InputImageLinkText == null) return;
                    GetDispImage(InputImageLinkText, true);
                    break;
                case "PositionFix":
                    PositionFixText = obj.LinkName;
                    if (PositionFixText == null) return;
                    GetPositionFix(PositionFixText);
                    break;
                default:
                    break;
            }
        }

        public override bool ExeModule()
        {
            try
            {
                Stopwatch.Restart();
                Application.Current.Dispatcher.Invoke(() =>
                {
                    mWindowH.Clear();
                    Loaded();
                    _DrawOutlineList.Clear();
                });
                if (SelectedTemplate != null && SelectedTemplate.Data != null
                    && SelectedTemplate.Data._DrawOutlineList != null &&
                    SelectedTemplate.Data._DrawOutlineList.Count != 0)
                {
                    if (IsPositionFix && PositionFixTool != null)
                    {
                        foreach (var item in SelectedTemplate.Data._DrawOutlineList)
                        {
                            PositionFixTool.BasicParam.InitialShape = item;
                            PositionFixTool.Run();
                            PositionFixTool.Result.CorrectedShape.BorderColor = item.BorderColor;
                            _DrawOutlineList.Add((CMvdPointSetF)PositionFixTool.Result.CorrectedShape);
                        }
                    }
                    else
                    {
                        _DrawOutlineList = SelectedTemplate.Data._DrawOutlineList.ToList();
                    }
                    mWindowH.DrawPointSetFList(_DrawOutlineList);
                    ChangeModuleRunStatus(eRunStatus.OK);

                    return true;
                }
                else
                {
                    ChangeModuleRunStatus(eRunStatus.NG);
                    return false;
                }
            }
            catch (Exception ex)
            {
                ChangeModuleRunStatus(eRunStatus.NG);
                return false;
            }

        }

        public override bool ExeModule(string TemplateName)
        {
            return ExeModule();
        }

        public override void AddOutputParams()
        {
            base.AddOutputParams();
            AddOutputParam("轨迹点", "List<Point>", _DrawOutlineList);
        }

        #endregion

    }
}
